﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.PTG;
using Warehouse.API.Applcation.Command.InjureCommand;
using Warehouse.Domain;
using Warehouse.Infrstructre;
using Warehouse.Infrstructre.Interface;

namespace Warehouse.API.Applcation.CommandHandlers.InjureCommandHandler
{

    /// <summary>
    /// 报损添加
    /// </summary>
    public class InjureAddCommandHandler : IRequestHandler<InjureAddCommand, int>
    {
        IInjureRepository IRep;
        EFCoreDBcontext dbContext;
        IInProductRepository ipRep;
        IMapper _mapper;

        public InjureAddCommandHandler(IInjureRepository IRep,
        EFCoreDBcontext dbContext,
        IInProductRepository ipRep,
        IMapper _mapper)
        {
            this.IRep = IRep;
            this.dbContext = dbContext;
            this.ipRep = ipRep;
            this._mapper = _mapper;
        }

        public async Task<int> Handle(InjureAddCommand request, CancellationToken cancellationToken)
        {

            using (var tran = await dbContext.Database.BeginTransactionAsync((System.Data.IsolationLevel.Serializable)))
            {

                try
                {
                    var s = _mapper.Map<Injure>(request.addDto);
                    s.InjureType = 1;
                    s.InjureStart = 1;

                    // 先处理 procurement1
                    await IRep.AddAsync(s);

                    foreach (var item in request.addDto.injureDetails)
                    {
                        InProduct detail = new InProduct
                        {

                            AuditStart = 1,
                            InjureCode = s.InjureCode,
                            ProductId = item.ProductId,
                            InjureNum = item.InjureNum,
                            StorehouseId = item.StorehouseId,
                            office_id = item.office_id,
                            user_id = item.user_id
                        };
                        await ipRep.AddAsync(detail);
                    }

                    // 提交事务
                    await tran.CommitAsync();

                    return 1;  // 返回最终的结果
                }
                catch (Exception)
                {
                    // 回滚事务
                    await tran.RollbackAsync();
                    throw;
                }
            }
        }
    }
}
